<template>
  <div id="userManagePage" flex="auto">
    <a-flex justify="space-between" style="margin-bottom: 16px">
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/add_picture" target="_blank">+ 创建图片</a-button>
        <a-button type="primary" href="/add_picture/batch" target="_blank" ghost>+ 批量创建图片</a-button>
        <a-button
          type="primary"
          ghost
          :icon="h(BarChartOutlined)"
          :href="`/space_analyze?queryPublic=1`"
          target="_blank"
        >
          分析公共图片
        </a-button>
        <a-button
          type="primary"
          ghost
          :icon="h(BarChartOutlined)"
          :href="`/space_analyze?queryAll=1`"
          target="_blank"
        >
          分析所有图片
        </a-button>
      </a-space>
    </a-flex>
    <div class="module">
      <!-- 搜索框 -->
      <div class="search">
        <a-form layout="inline" :model="searchParam" @finish="doSearch">
          <a-form-item label="关键词" name="searchText">
            <a-input
              v-model:value="searchParam.searchText"
              placeholder="从名称和简介搜索"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="类型" name="category">
            <a-input v-model:value="searchParam.category" placeholder="请输入类型" allow-clear />
          </a-form-item>
          <a-form-item label="审核状态" name="reviewStatus">
            <a-select
              v-model:value="searchParam.reviewStatus"
              :options="PIC_REVIEW_STATUS_OPTIONS"
              placeholder="请输入审核状态"
              style="min-width: 180px"
              allow-clear
            />
          </a-form-item>

          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="120" />
        </template>
        <!-- 标签 -->
        <template v-if="column.dataIndex === 'tags'">
          <div class="tags-tab">
            <a-space wrap>
              <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag" style="margin: 0">{{ tag }}</a-tag>
            </a-space>
          </div>

        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewMessage'">
          <div>审核状态：{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核人：{{ record.reviewerId }}</div>
        </template>

        <template v-else-if="column.key === 'action'">
          <div class="action">
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
              type="link"
              @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
              >通过
            </a-button>
            <a-popconfirm
              title="确认拒绝通过？"
              ok-text="确认"
              cancel-text="取消"
              type="link"
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
              @confirm="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
              @cancel="cancel"
            >
              <a href="#" style="color:red;">拒绝</a>
            </a-popconfirm>

            <!-- 编辑图片 -->
            <a-button type="link" @click="doEdit(record.id)" target="_blank"
              >编辑
            </a-button>
            <!-- 删除图片 -->
            <a-button danger @click="showDeleteModal(record.id)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
  </div>

  <!-- 对话框组件 -->
  <DeletePictureDialog ref="DeletePictureDialogRef" @refresh="fetchPictureData" />
</template>
<script lang="ts" setup>
import { computed, h, onMounted, reactive, ref } from 'vue'
import { doReviewPictureUsingPost, listPictureByPageUsingPost } from '@/api/pictureController.ts'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import DeletePictureDialog from '@/pages/admin/components/DeletePictureDialog.vue'
import {
  PIC_REVIEW_STATUS_ENUM,
  PIC_REVIEW_STATUS_MAP,
  PIC_REVIEW_STATUS_OPTIONS,
} from '@/constants/picture.ts'
import { useRouter } from 'vue-router'
import { BarChartOutlined } from '@ant-design/icons-vue'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
    align: 'center',
  },
  {
    title: '图片',
    dataIndex: 'url',
    align: 'center',
  },
  {
    title: '名称',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '类型',
    dataIndex: 'category',
    align: 'center',
  },
  {
    title: '标签',
    dataIndex: 'tags',
    align: 'center',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
    align: 'center',
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]

// 定义数据
const dataList = ref<API.Picture[]>([])
const total = ref(0)

// 搜索条件
const searchParam = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParam.current,
    pageSize: searchParam.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

// 当表格发生变化时，刷新页面数据
const doTableChange = (page: any) => {
  searchParam.current = page.current
  searchParam.pageSize = page.pageSize
  fetchPictureData()
}

// 获取图片信息数据
const fetchPictureData = async () => {
  const pictureData = await listPictureByPageUsingPost({
    nullSpaceId: true,
    ...searchParam,
  })
  if (pictureData.data.code === 0 && pictureData.data.data) {
    dataList.value = pictureData.data.data.records ?? []
    total.value = pictureData.data.data.total ?? 0
  } else {
    message.error('获取图片信息失败，' + pictureData.data.message)
  }
}

// 搜索事件
const doSearch = () => {
  searchParam.current = 1
  fetchPictureData()
}

// 引入删除子组件方法
const DeletePictureDialogRef = ref(null)
// 删除图片所需参数
const deleteId = ref<number>(0)
// 展示删除图片对话框
const showDeleteModal = (id: number) => {
  // 调用删除子组件方法
  DeletePictureDialogRef.value!.openDialog(id)
}

// 审核操作
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const reviewMessage =
    reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
  const res = await doReviewPictureUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  })
  if (res.data.code === 0) {
    message.success('审核操作成功')
    // 重新获取列表
    fetchPictureData()
  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}

const router = useRouter()

// 编辑
const doEdit = (id: number) => {
  router.push('/add_picture?id=' + id)
}

const cancel = (e: MouseEvent) => {
  console.log(e)
  message.error('已取消')
}

// 钩子函数，页面加载时获取数据
onMounted(() => {
  fetchPictureData()
})
</script>

<style scoped>
.module {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.search {
  margin-left: 20px;
}

.action {
  width: 65px;
  margin: 0 auto;
}
.tags-tab {
  width: 80px;
  margin: 0 auto;
}
</style>
